import pandas as pd
import json
import numpy as np

from django.core.management.base import BaseCommand
from htstool.models import *

class Command(BaseCommand):
	
	ALPHA=list('ABCDEFGHIJKLMNOP')

	def handle(self, *args, **options):
		exp, nonrad_grp, irrad_grp=self.create_exp()

		grp=[]
		for f in ['RKO.csv', 'T29.csv']:
			nonrad, irrad=self.get_dfs(f, num_plates=20, mixed=True)
			grp.append(nonrad)
			grp.append(irrad)
		for f in ['V432_IR.csv','wV432_IR.csv']:
			grp.append(self.get_dfs(f))
		for f in ['V432_NR.csv','wV432_NR.csv']:
			grp.append(self.get_dfs(f))
		
		self.save_groups(grp, exp, nonrad_grp, irrad_grp)
		exp.save()


	def get_dfs(self, f, num_plates=10, mixed=False):
		content=pd.read_csv(f,skipfooter=155, header=None)

		chunks=np.array_split(content, num_plates) 


		df_pair=[]
		for chunk in chunks:
			barcode=chunk.values[2][2]
			df=chunk[8:-1].drop([24], axis=1)
 			df.columns=['0'+str(n+1) if n < 9 else str(n+1) for n in df.columns]
			df.index=self.ALPHA
			df_pair.append((barcode,df.astype(float)))

		if mixed==True:
			nonrad=df_pair[:len(df_pair)/2]
			irrad=df_pair[len(df_pair)/2:]
			return [nonrad, irrad]
		else:
			return df_pair
		
	def save_groups(self, groups, exp, nonrad, irrad):
		for df_list in groups:
			for pair in df_list:
				barcode, df=pair
				# 'ODL_RKO_IR_10_R2'
				lib, cellline, cond, concen, repl=barcode.split('_')

				if cond=='IR':
					group=irrad 
				elif cond=='NR':
					group=nonrad

				df_dict=json.loads(df.to_json())
				dataset=Dataset(data=df_dict)
				dataset.save()

				rawplate=RawPlate(platename=barcode[:-3], cellline=cellline, replicate=int(repl[-1]),
						condition=cond, concentration=concen, dimension=df.shape, 
						data=dataset)
				rawplate.save()
				
				# specifiy the commom attr
				# TODO - automatic common attr getter
				group.platecommonattr={'condition':cond, 'dimension':df.shape}
				group.plates.append(rawplate)
			group.save()


	def create_exp(self):

		nonrad=PlateGroup(groupname='RAW readout non-radiated plates', plate_type=PlateGroup.RAW)
		nonrad.save()
		irrad=PlateGroup(groupname='RAW readout irradiated plates', plate_type=PlateGroup.RAW)
		irrad.save()

		exp=Experiment(expname='Sharma screen2 cancer drug library', group='Sharma/Azi', screen='screen 2',
				library='ODL_DTP cancer drugs', description='blabla', 
				plategroups=[nonrad, irrad])

		exp.save()

		return (exp, nonrad, irrad)
